package com.mall.user.services;/**
 * Created by ciggar on 2019/7/30.
 */

import com.alibaba.fastjson.JSON;
import com.mall.user.IMemberService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.converter.MemberConverter;
import com.mall.user.converter.UserConverterMapper;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.*;
import com.mall.user.utils.AESUtil;
import com.mall.user.utils.ExceptionProcessorUtils;
import com.mall.user.utils.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 *  ciggar
 * create-date: 2019/7/30-下午11:51
 */
@Slf4j
@Service
@Component
public class MemberServiceImpl implements IMemberService {

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserVerifyMapper userVerifyMapper;

//    @Autowired
//    IUserLoginService userLoginService;

    @Autowired
    MemberConverter memberConverter;

    @Autowired
    UserConverterMapper userConverterMapper;

    /**
     * 根据用户id查询用户会员信息
     * @param request
     * @return
     */
    @Override
    public QueryMemberResponse queryMemberById(QueryMemberRequest request) {
        QueryMemberResponse queryMemberResponse=new QueryMemberResponse();
        try{
            request.requestCheck();
            Member member=memberMapper.selectByPrimaryKey(request.getUserId());
            if(member==null){
                queryMemberResponse.setCode(SysRetCodeConstants.DATA_NOT_EXIST.getCode());
                queryMemberResponse.setMsg(SysRetCodeConstants.DATA_NOT_EXIST.getMessage());
            }
            queryMemberResponse=memberConverter.member2Res(member);
            queryMemberResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            queryMemberResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        }catch (Exception e){
            log.error("MemberServiceImpl.queryMemberById Occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(queryMemberResponse,e);
        }
        return queryMemberResponse;
    }

    @Override
    public HeadImageResponse updateHeadImage(HeadImageRequest request) {
        HeadImageResponse response=new HeadImageResponse();
        //TODO
        return response;
    }

    @Override
    public UpdateMemberResponse updateMember(UpdateMemberRequest request) {
        return null;
    }


    /**
     * 用户注册验证
     * @param uid
     * @param username
     * @return
     */
    @Override
    public Integer verifyUser(String uid, String username) {
        //验证数据的合法性
        //Member member = memberMapper.selectByPrimaryKey(uid);
        Example example = new Example(UserVerify.class);
        example.createCriteria().andEqualTo("uuid", uid)
                .andEqualTo("username", username);
        List<UserVerify> userVerifies = userVerifyMapper.selectByExample(example);
        if (userVerifies == null && userVerifies.size() == 0) {
            return 0;
        }

        Example memberExample = new Example(Member.class);
        memberExample.createCriteria().andEqualTo("username", username);
        List<Member> members = memberMapper.selectByExample(memberExample);
        Member member = members.get(0);
        if (member == null || member.getUsername() == null) {
            return 0;
        }
        // 更新member表中的数据
        Integer resultUpdateMember = updateMemberByMember(member);
        // 更新 user_verify表中的数据
        Integer resultUpdateUserVerified = updateUserVerifyByUsername(username);
        return (resultUpdateUserVerified == 1) &&resultUpdateMember == 1 ? 1 : 0;
    }

    private Integer updateMemberByMember(Member member) {
        member.setIsVerified("Y");
        member.setUpdated(new Date());
        return memberMapper.updateByPrimaryKey(member);
    }

    private Integer updateUserVerifyByUsername(String username) {
        UserVerify userVerify = new UserVerify();
        userVerify.setIsVerify("Y");
        userVerify.setUsername(username);
        Example example = new Example(UserVerify.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", username);
        return userVerifyMapper.updateByExampleSelective(userVerify, example);
    }

    @Override
    public UserLoginResponse userLogin(UserLoginRequest request) {
        UserLoginResponse response = new UserLoginResponse();

        //检查参数
        request.requestCheck();
        //将用户密码解密
        //AESUtil aesUtil = new AESUtil(request.getPassword());
        //String password = aesUtil.decrypt();
        String password = request.getPassword();
        Example memberExample = new Example(Member.class);
        memberExample.createCriteria().andEqualTo("username", request.getUserName())
                .andEqualTo("password", password);
        List<Member> members = memberMapper.selectByExample(memberExample);
        if (members == null || members.size() == 0) {
            response.setCode(SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode());
            response.setMsg(SysRetCodeConstants.USERORPASSWORD_ERRROR.getMessage());
            return response;
        }
        Member member = members.get(0);
        response = userConverterMapper.converter(member);
        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        //设置token，，并存入response对象中
        UserInfo userInfo = new UserInfo();
        userInfo.setUid(member.getId());
        userInfo.setUsername(member.getUsername());
        String userInfoStr = JSON.toJSONString(userInfo);
        JwtTokenUtils jwtToken = JwtTokenUtils.builder().msg(userInfoStr).build();
        String token = jwtToken.creatJwtToken();
        response.setToken(token);
        return response;
    }

//    @Override
//    public UpdateMemberResponse updateMember(UpdateMemberRequest request) {
//        UpdateMemberResponse response = new UpdateMemberResponse();
//        try{
//            request.requestCheck();
//            CheckAuthRequest checkAuthRequest = new CheckAuthRequest();
//            checkAuthRequest.setToken(request.getToken());
//            CheckAuthResponse authResponse = userLoginService.validToken(checkAuthRequest);
//            if (!authResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
//                response.setCode(authResponse.getCode());
//                response.setMsg(authResponse.getMsg());
//                return response;
//            }
//            Member member = memberConverter.updateReq2Member(request);
//            int row = memberMapper.updateByPrimaryKeySelective(member);
//            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
//            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
//            log.info("MemberServiceImpl.updateMember effect row :"+row);
//        }catch (Exception e){
//            log.error("MemberServiceImpl.updateMember Occur Exception :"+e);
//            ExceptionProcessorUtils.wrapperHandlerException(response,e);
//        }
//        return response;
//    }
}
